<template>
  <!-- 用 Element Plus 的 Container 布局（也可不用，按需调整），这里简单用一个 div 包裹表单 -->
  <div class="register-container">
    <!-- ElForm 表单组件，通过 rules 配置校验规则，model 绑定表单数据 -->
    <el-form
        :model="form"
        :rules="rules"
        ref="registerForm"
        label-width="80px"
        class="register-form"
    >
      <!-- 账户名 -->
      <el-form-item label="账户名" prop="accountName" >
        <!-- ElInput 输入框，双向绑定 form.accountName -->
        <el-input v-model="form.accountName" placeholder="请输入账户名" ></el-input>
      </el-form-item>
      <!-- 用户名 -->
      <el-form-item label="用户名" prop="username" >
        <!-- ElInput 输入框，双向绑定 form.username -->
        <el-input v-model="form.username" placeholder="请输入用户名" ></el-input>
      </el-form-item>

      <!-- 手机号 -->
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="form.phone" placeholder="请输入11位手机号"></el-input>
      </el-form-item>

      <!-- 验证码 -->
      <el-form-item label="验证码" prop="code">
        <el-input
            v-model="form.verifyCode"
            placeholder="请输入验证码"
            style="width: 70%"
        ></el-input>
        <!-- ElButton 按钮，点击触发 getCode 方法（需自己实现逻辑，比如调用接口发验证码） -->
        <el-button
            type="primary"
            @click="getCode"
            :disabled="isCounting"
            style="margin-left: 40px;"
        >
          获取验证码
        </el-button>
      </el-form-item>

      <!-- 设置密码 -->
      <el-form-item label="设置密码" prop="password">
        <el-input
            v-model="form.password"
            placeholder="请输入6 - 16位密码"
            type="password"
            show-password
            clearable
        ></el-input>
      </el-form-item>

      <!-- 确认密码 -->
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input
            v-model="form.confirmPassword"
            placeholder="请输入确认密码"
            type="password"
            show-password
            clearable
        ></el-input>
      </el-form-item>

      <!-- 注册按钮 -->
      <el-form-item>
        <el-button type="primary"
        @click="handleRegister"
        style="width: 100%;"
        >
        注册
        </el-button>
      </el-form-item>

      <!-- 已有账户跳转 -->
      <el-form-item>
        <p class="login-link">
<!--          <a href="/login">去登陆</a>-->
          <span>已有账户，<router-link to="/login">去登陆</router-link></span>
        </p>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { ElMessage } from "element-plus";
import { getCodeApi, handleRegisterApi } from "@/api/regapi.js";

const isCounting = ref(false);
const countdown = ref(60);
const buttonText = ref('获取验证码');

const form = reactive({
  accountName: '',
  username: '',
  phone: '',
  verifyCode: '',
  password: '',
  confirmPassword: '',
  scene:'register'
})

// todo 发送验证码
const getCode = async () => {
  // 先校验手机号格式
  const phonePattern = /^1[3-9]\d{9}$/;
  if (!phonePattern.test(form.phone)) {
    ElMessage.error('请输入正确的11位手机号');
    return;
  }

  if (isCounting.value) return; // 防止重复点击

  isCounting.value = true;
  buttonText.value = `${countdown.value}s后重试`;
  let timer = setInterval(() => {
    countdown.value--;
    buttonText.value = `${countdown.value}s后重试`;

    if (countdown.value <= 0) {
      clearInterval(timer);
      isCounting.value = false;
      buttonText.value = '获取验证码';
      countdown.value = 60;
    }
  }, 1000);

  try {
    // todo 调用封装的发送验证码接口
    const response = await getCodeApi(form.phone, form.scene);

    if (response.data.code === 200) {
      ElMessage.success('验证码已发送，请注意查收');
    } else {
      ElMessage.error(response.data.message || '验证码发送失败'); //throw new
    }
  } catch (error) {
    clearInterval(timer);
    isCounting.value = false;
    buttonText.value = '获取验证码';
    countdown.value = 60;

    ElMessage.error(error.message || '验证码发送失败，请稍后重试');
    console.error('验证码发送失败:', error);
  }
};

// todo 进行注册
const handleRegister = async () => {
  // // 构造请求参数（与你期望的格式完全一致）
  // const registerData = {
  //   accountName: form.accountName,  // 正确：读取表单绑定的 form.accountName
  //   username: form.username,        // 正确：读取 form.username
  //   password: form.password,        // 正确：读取 form.password
  //   confirmPassword: form.confirmPassword,
  //   phone: form.phone,
  //   verifyCode: form.verifyCode,  // 注意：后端参数名是 verifyCode，前端表单绑定的是 form.code，需保持一致
  //
  //
  // };
  //
  // // 打印参数确认格式（调试用）
  // console.log("注册请求参数：", registerData);

  try {
    // todo 调用封装的注册接口
    const response = await handleRegisterApi(form);
    console.log('注册成功', response.data);
    ElMessage.success('注册成功');
  } catch (error) {
    console.error('注册失败', error.response?.data?.message || error.message);
    ElMessage.error(error.response?.data?.message || '注册失败，请稍后重试');
  }
};



// 表单校验规则
const rules = {
  accountName: [
    { required: true, message: '请输入账户名', trigger: 'blur' }
  ],
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  phone: [
    {
      required: true,
      message: '请输入手机号',
      trigger: 'blur'
    },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的11位手机号',
      trigger: 'blur'
    }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ],
  password: [
    {
      required: true,
      message: '请输入密码',
      trigger: 'blur'
    },
    {
      pattern: /^.{6,16}$/,
      message: '密码需为6 - 16位',
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    {
      required: true,
      message: '请确认密码',
      trigger: 'blur'
    },
    {
      validator: (rule, value, callback) => {
        if (value!== form.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}
</script>

<style scoped>
/* 外层容器，让表单在页面中水平垂直居中 */
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;

  background-color: #eefaff; /* 可根据实际调整背景色，贴近设计图的浅蓝背景 */
}


/* 表单区域样式 */
.register-form {
  width: 800px;
  height: 600px;
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  background-color: #fff;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

  /* 启用 Flex 布局 */
  display: flex;
  flex-direction: column;
  justify-content: space-between; /* 使内容均匀分布 */
}

/* 调整输入框样式，让输入框底色为浅绿，和设计图匹配 */
.el-input__wrapper {
  background-color: #0fe20f;
}

/* 按钮样式，确保是蓝色（Element Plus 的 primary 按钮默认是蓝色，若需自定义更独特蓝色可改 background-color 等） */

/* 登录链接样式 */
.login-link {
  text-align: center;
  margin: 0;
  color: #606266;
}

.login-link a {
  color: #409eff;
  text-decoration: none;
}
</style>

